﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SchoolManagementSystem.Classes
{
    public class Logger
    {
        private string logFilePath="log.txt";
        FileStream writtenFileStream;
        BufferedStream bufferedStream;
        byte[] buffer;
        List<byte[]> addBytes;
        bool hasInit = false;

        public Logger()
        {
            if (File.Exists(logFilePath))
                this.writtenFileStream = new FileStream("log.txt", FileMode.Open);
            else
                this.writtenFileStream = new FileStream("log.txt", FileMode.Create);
            this.bufferedStream = new BufferedStream(writtenFileStream);
            buffer = new byte[bufferedStream.Length];
            addBytes = new List<byte[]>();
            init();
        }

        private void init()
        {
            if(!hasInit)
            {
                int length = 2048;
                int bytesRead = 0;
                byte[] array = new byte[length];
                int offset = 0;
                while ((bytesRead = bufferedStream.Read(array, 0, length)) > 0)
                {
                    for (int i = 0; i < bytesRead; i++) 
                    {
                        buffer[i+offset] = array[i];
                    }
                    offset += bytesRead;
                }
                writtenFileStream.Write(buffer, 0, buffer.Length);
            }
        }

        public void AddToLog(string info)
        {
            addBytes.Add(System.Text.Encoding.Default.GetBytes("\n" + info + "\n"));
        }

        private void Flush()
        {
            foreach (var item in addBytes)
            {
                writtenFileStream.Write(item, 0, item.Length);
            }
            addBytes.Clear();
            bufferedStream.Flush();
            writtenFileStream.Flush();
            //init();
        }

        public void showLogInfomation()
        {
            Flush();
            if (!File.Exists(logFilePath))
                File.Create(logFilePath).Close();
            Process.Start("notepad.exe", logFilePath);
        }

        public void close()
        {
            Flush();
            bufferedStream.Close();
            writtenFileStream.Close();
        }
    }
}
